package com.dummies.android.taskreminder;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

public class OnAlarmReceiver extends BroadcastReceiver {

	private Context mContext;
	MediaPlayer mediaPlayer;

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d("==OnAlarmReceiver==", "==onReceive==");
		// TODO Auto-generated method stub
		this.mContext = context;
		final long rowid = intent.getExtras().getLong(
				RemindersDbAdapter.KEY_ROWID);
		final String title = intent.getExtras().getString(
				RemindersDbAdapter.KEY_TITLE);
		final String body = intent.getExtras().getString(
				RemindersDbAdapter.KEY_BODY);
		WakeReminderIntentService.acquireStaticLock(context);
		Intent i = new Intent(context, ReminderService.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.putExtra(RemindersDbAdapter.KEY_ROWID, rowid);
		i.putExtra(RemindersDbAdapter.KEY_TITLE, title);

		// thong bao reminder bang sound
		playMedia(context);
		// hien thi dialog reminder
		showAlarmDialog(context, rowid, title, body);

		context.startService(i);
	}

	private void playMedia(Context context) {
		try {
			Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setDataSource(context, uri);
			mediaPlayer.prepare();
			mediaPlayer.setLooping(true);
			mediaPlayer.start();
		} catch (Exception e) {
			Log.d("==ERROR==", "" + e);
		}
	}

	private void showAlarmDialog(Context context, final long rowid,
			final String title, final String body) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("Reminder");
		builder.setMessage(title);
		builder.setNegativeButton("Sleep", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				setReminder(rowid, title, body);
				mediaPlayer.stop();
				Log.d("==Sleep==", "SLEEP" + rowid);
			}
		});
		builder.setPositiveButton("Cancel", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				mediaPlayer.stop();
				//cancel regular alarms
				PendingIntent pi = getPendingIntent(mContext, (int)rowid);
				AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
				alarmManager.cancel(pi);
				pi.cancel();
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.getWindow().setType(
				WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		alertDialog.show();
	}

	@SuppressLint("SimpleDateFormat")
	protected void setReminder(long rowid, String title, String body) {
		Calendar mCalendar = Calendar.getInstance();
		mCalendar.set(Calendar.MONTH, mCalendar.get(Calendar.MONTH) + 1);
		int minutes = mCalendar.get(Calendar.MINUTE) + 2;
		mCalendar.set(Calendar.MINUTE, minutes);

		Log.d("==SLEEP==",
				mCalendar.get(Calendar.YEAR) + "-"
						+ mCalendar.get(Calendar.MONTH) + "/"
						+ mCalendar.get(Calendar.DAY_OF_MONTH) + "|"
						+ mCalendar.get(Calendar.HOUR_OF_DAY) + ":" + minutes);

		RemindersDbAdapter mDbHelper = new RemindersDbAdapter(mContext);
		mDbHelper.open();
		SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
				ReminderEditActivity.DATE_TIME_FORMAT);
		String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
		if (mDbHelper.updateReminder(rowid, title, body, reminderDateTime)) {
			new ReminderManager(mContext).setUpdateReminder(rowid, mCalendar,
					title);

			Toast.makeText(mContext,
					title + " Reminder Snoozed for " + 2 + " Minutes ",
					Toast.LENGTH_LONG).show();
		}
	}

	// get a PendingIntent
	PendingIntent getPendingIntent(Context context, int id) {
		Intent intent = new Intent(context, OnAlarmReceiver.class).putExtra(
				RemindersDbAdapter.KEY_TITLE, id);
		return PendingIntent.getBroadcast(context, id, intent,
				PendingIntent.FLAG_UPDATE_CURRENT);
	}
}
